//
//  JFCommodityViewController.m
//  JFLiveVideoDemo
//
//  Created by cc on 2020/2/26.
//  Copyright © 2020 dev. All rights reserved.
//

#import "XLH5ViewController.h"
#import <WebKit/WebKit.h>
#import "XLConversationInputViewDef.h"

static void *WKWebBrowserContext = &WKWebBrowserContext;

@interface XLH5ViewController ()
<
WKNavigationDelegate,
WKUIDelegate
>

@property(nonatomic,strong)WKWebView *contentWebView;
@property(nonatomic,strong)UIProgressView *progressView;

@end

@implementation XLH5ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self.view addSubview:self.contentWebView];
    [self.view addSubview:self.progressView];
    [self layoutConstraints];
    [self loadData];
}

- (void)onClickBack {
    
    if ([self.contentWebView canGoBack]) {
        
        [self.contentWebView goBack];
    }else {
        
        [self.navigationController popViewControllerAnimated:YES];
    }
}

- (void)layoutConstraints {
    
    self.contentWebView.frame = CGRectMake(0, 0,
                                           self.view.bounds.size.width,
                                           self.view.bounds.size.height - kXLCIBottomSafeHeight);
    self.progressView.frame = CGRectMake(0, 0, self.view.bounds.size.width, 2);
}

- (void)loadData {
    
    NSString *urlStr = self.urlStr.length ? self.urlStr : self.url ? self.url.absoluteString : @"";
    if (![urlStr hasPrefix:@"https"]) { 
        urlStr = [urlStr stringByReplacingOccurrencesOfString:@"http" withString:@"https"];
    }
    NSURL *url = [NSURL URLWithString:urlStr];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    [self.contentWebView loadRequest:request];
}

#pragma mark - WKNavigationDelegate
//开始加载
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation{
    //开始加载的时候，让加载进度条显示
    self.progressView.hidden = NO;
}

//网页加载完成
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
    // 获取加载网页的标题
    //    self.navigationItem.title = self.contentWebView.title;
}
//内容返回时调用
- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation {
    
}

//服务器请求跳转的时候调用
- (void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(WKNavigation *)navigation {
    
}

// 内容加载失败时候调用
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation withError:(NSError *)error{
    NSLog(@"%@",error);
}

- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
    //如果是跳转一个新页面
    if (navigationAction.targetFrame == nil) {
        [webView loadRequest:navigationAction.request];
    }
    
    //    NSURL *URL = navigationAction.request.URL;
    //    [self dealSomeThing:URL];
    
    WKNavigationActionPolicy actionPolicy = WKNavigationActionPolicyAllow;//允许
    
    //    NSString *urlString = [[navigationAction.request URL] absoluteString];
    //    
    //    urlString = [urlString stringByRemovingPercentEncoding];
    
    decisionHandler(actionPolicy);
    
}


- (void)webViewWebContentProcessDidTerminate:(WKWebView *)webView{
    
    [webView reload];
}

- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:message?:@"" preferredStyle:UIAlertControllerStyleAlert];
    [alertController addAction:([UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        completionHandler();
    }])];
    [self presentViewController:alertController animated:YES completion:nil];
    
}
- (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL))completionHandler{
    //    DLOG(@"msg = %@ frmae = %@",message,frame);
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:message?:@"" preferredStyle:UIAlertControllerStyleAlert];
    [alertController addAction:([UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        completionHandler(NO);
    }])];
    [alertController addAction:([UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        completionHandler(YES);
    }])];
    [self presentViewController:alertController animated:YES completion:nil];
}
- (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString * _Nullable))completionHandler
{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:prompt message:@"" preferredStyle:UIAlertControllerStyleAlert];
    [alertController addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        textField.text = defaultText;
    }];
    [alertController addAction:([UIAlertAction actionWithTitle:@"完成" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        completionHandler(alertController.textFields[0].text?:@"");
    }])];
    
    [self presentViewController:alertController animated:YES completion:nil];
}


//KVO监听进度条
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    
    if ([keyPath isEqualToString:NSStringFromSelector(@selector(estimatedProgress))] && object == self.contentWebView) {
        [self.progressView setAlpha:1.0f];
        BOOL animated = self.contentWebView.estimatedProgress > self.progressView.progress;
        [self.progressView setProgress:self.contentWebView.estimatedProgress animated:animated];
        
        // Once complete, fade out UIProgressView
        if(self.contentWebView.estimatedProgress >= 1.0f) {
            [UIView animateWithDuration:0.3f delay:0.3f options:UIViewAnimationOptionCurveEaseOut animations:^{
                [self.progressView setAlpha:0.0f];
            } completion:^(BOOL finished) {
                [self.progressView setProgress:0.0f animated:NO];
            }];
        }
    }
    else if ([keyPath isEqualToString:@"title"]) {
        if (object == self.contentWebView)
        {
            self.navigationItem.title = self.contentWebView.title;
        }
        else {
            [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
        }
    }
    else{
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
    
    
}

#pragma mark - getters and setters
- (WKWebView *)contentWebView {
    if (!_contentWebView) {
        _contentWebView = [[WKWebView alloc] init];
        _contentWebView.backgroundColor = [UIColor whiteColor];
        _contentWebView.opaque = YES;
        //适应你设定的尺寸
        [_contentWebView sizeToFit];
        _contentWebView.scrollView.showsVerticalScrollIndicator = NO;
        // 设置代理
        _contentWebView.navigationDelegate = self;
        _contentWebView.UIDelegate = self;
        //kvo 添加进度监控
        [_contentWebView addObserver:self forKeyPath:NSStringFromSelector(@selector(estimatedProgress)) options:0 context:WKWebBrowserContext];
        [_contentWebView addObserver:self forKeyPath:@"title" options:NSKeyValueObservingOptionNew context:NULL];
        
        //设置网页的配置文件
        WKWebViewConfiguration * Configuration = [[WKWebViewConfiguration alloc]init];
        // 此处一定要做判断，因为是iOS9之后才有的方法，否则在iOS8下会崩溃
        if ([[UIDevice currentDevice].systemVersion floatValue] >= 9.0) {
            //允许视频播放
            Configuration.allowsAirPlayForMediaPlayback = YES;
            // 允许在线播放
            Configuration.allowsInlineMediaPlayback = YES;
            //开启手势触摸 默认设置就是NO。在ios8系统中会导致手势问题，程序崩溃
            _contentWebView.allowsBackForwardNavigationGestures = NO;
        }
        // 允许可以与网页交互，选择视图
        Configuration.selectionGranularity = YES;
        // web内容处理池
        Configuration.processPool = [[WKProcessPool alloc] init];
        //自定义配置,一般用于 js调用oc方法(OC拦截URL中的数据做自定义操作)
        WKUserContentController * UserContentController = [[WKUserContentController alloc]init];
        // 是否支持记忆读取
        Configuration.suppressesIncrementalRendering = YES;
        // 允许用户更改网页的设置
        Configuration.userContentController = UserContentController;
    }
    return _contentWebView;
}

- (UIProgressView *)progressView {
    if (!_progressView) {
        _progressView = [[UIProgressView alloc]initWithProgressViewStyle:UIProgressViewStyleDefault];
        [_progressView setTrackTintColor:[UIColor colorWithRed:240.0/255 green:240.0/255 blue:240.0/255 alpha:1.0]];
        _progressView.progressTintColor = [UIColor redColor];
    }
    return _progressView;
}

// 记得dealloc
- (void)dealloc {
    
    [self.contentWebView removeObserver:self forKeyPath:@"title" context:nil];
    @try {
        [self.contentWebView removeObserver:self forKeyPath:NSStringFromSelector(@selector(estimatedProgress))];
    } @catch (NSException *exception) {
        NSLog(@"%@",exception);
    }
}

@end
